package com.kye.base.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 02/01/2018
 * @updated : 02/01/2018
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public class GsonUtils {

    public static String formatPrettyJson(String json) {
        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .create();
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(json);
        return gson.toJson(element);
    }

    public static String toJsonString(Object jsonObject, boolean isFormat) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        if (isFormat) {
            gsonBuilder.setPrettyPrinting();
        }
        gsonBuilder.serializeNulls();
        Gson gson = gsonBuilder.create();
        return gson.toJson(jsonObject);
    }

    public static String toJsonString(Object jsonObject) {
        return toJsonString(jsonObject, false);
    }

    public static <T> T toJsonObject(String jsonString, Class<T> clazz) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        return gson.fromJson(jsonString, clazz);
    }

    public static <T> T toJsonObject(String jsonString, Type typeOfT) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        return gson.fromJson(jsonString, typeOfT);
    }

    public static <T> List<T> toJsonList(String jsonStringList, Class<T> clazz) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        return gson.fromJson(jsonStringList, new TypeToken<List<T>>(){}.getType());
    }
}
